package com.stenio.fancat.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stenio.fancat.common.FanCatException;
import com.stenio.fancat.domain.RechOrder;
import com.stenio.fancat.form.OrderForm;
import com.stenio.fancat.pay.Notice;
import com.stenio.fancat.pay.OrderResult;
import com.stenio.fancat.pay.Pay;

/**
 * 支付模块服务实现类
 */
@Service
public class PayService {

	private static final Logger logger = LoggerFactory.getLogger(PayService.class);

	@Autowired
	private Pay pay;
	@Autowired
	private RechOrderService rechOrderService;
	@Autowired
	private UserService userService;

	public OrderResult placeOrder(OrderForm form) throws FanCatException {
		// form.setBody("测试BODY");
		// form.setFee(1);

		OrderResult result = pay.placeOrder(form);
		return result;
	}

	public int processNotice(Notice notice) throws FanCatException {
		if (null == notice)
			throw new RuntimeException("微信通知XML解析结果为空");
		logger.info("WX notice==>{}", notice.toString());
		int i = pay.processNotice(notice);
		if (i > 0) {
			// do business.
			processOrder(notice);
		}
		return i;
	}

	/**
	 * 微信支付成功后处理订单、用户账户业务
	 * 
	 * @param notice
	 *            微信支付结果集
	 */
	@Transactional
	public void processOrder(Notice notice) {
		// 通过订单编号获取订单详
		String orderNo = notice.getOut_trade_no();
		RechOrder rechOrder = rechOrderService
				.selectOne(new EntityWrapper<RechOrder>().eq(RechOrder.RECH_ORDER_NO, orderNo));
		// 更新订单状态为已支付
		RechOrder entity = new RechOrder();
		entity.setStatus(0);
		entity.setRechOrderId(rechOrder.getRechOrderId());
		rechOrderService.updateById(entity);
		// 更新用户账户信息
		userService.saveUserAccount(rechOrder.getUserId(), rechOrder.getCandy(), 0);
	}

}
